$(document).ready(function() {
    //right
//	$.ajax({
//		type: 'GET',
//		url: '/api/coins/major',
//		dataType: 'json',
//		success: function(data) {
//			var msg = data.data;
//			$.each(msg, function(k,v) {
//				var html = '';
//				html += '<li id='+ v.coin_id +'><p class="left"><img src="http://img.bishijie.com/coinpic-' +v.coin_id+ '.jpg?imageMogr2/thumbnail/16x ">' + v.chinese_name +'(' + v.symbol +')<br/><span>' + v.price_usd + '</span></p>';
//				$.ajax({
//					type:"get",
//					url:"/api/coinchart/"+v.coin_id+"/peity",
//					async:false,
//					success:function(data2){
//						html += '<div class="char peity_box"><i class="num"></i><span class="line" data-peity="{height:20,width:70,fill:#f5f5f5}" style="display: none;">' + data2 + '</span><svg class="peity" height="20" width="70"></svg></div></li>';
//					}
//				});
//				$('.hangqing ul').append(html);
//			});
//
//			//行情链接
//			$('.hangqing ul li').click(function(){
//				var id = $(this).attr('id');
//				window.open('/hangqing/coin/'+id);
//			})
//
//			//画图加色
//          $('.peity_box').each(function(){
//              var _line = $('.line',this);
//              var _num = $('.num',this);
//              if(!_line.text()) return;
//              var _v = _line.text().split(',');
//              if(_v.length >= 2){
//                  if(_v[_v.length-1] > _v[_v.length-2]){
//                  	_num.addClass('rise').removeClass('fall');
//                  }else{
//                  	_num.addClass('fall').removeClass('rise');
//                  }
//              }else{
//                  _num.text(_v[_v.length-1]);
//              }
//              _line.peityZoom().peity('line');
//          });
//          $('.peity_box').css('display', 'block');
//          $('.rise').each(function(){
//          	var parent = this.parentNode;
//          	var ps =parent.previousSibling;
//          	var span = ps.getElementsByTagName('span');
//          	var img = '<img src=/images/rise.png>';
//          	var svg = parent.getElementsByTagName('svg')[0];
//          	var polyline = svg.getElementsByTagName('polyline')[0];
//          	$(polyline).attr('stroke','#e93b23');
//          	$(polyline).attr('stroke-width','0.3');
//          	$(span).css('color','#e93b23');
//          	$(span).append(img);
//          })
//          $('.fall').each(function(){
//          	var parent = this.parentNode;
//          	var ps =parent.previousSibling;
//          	var span = ps.getElementsByTagName('span');
//          	var img = '<img src=/images/fall.png>';
//          	var svg = parent.getElementsByTagName('svg')[0];
//          	var polyline = svg.getElementsByTagName('polyline')[0];
//          	$(polyline).attr('stroke','#2eab41');
//          	$(polyline).attr('stroke-width','0.3');
//          	$(span).css('color','#2eab41');
//          	$(span).append(img);
//          })
//          $('.peity').each(function(){
//          	var polygon = this.getElementsByTagName('polygon')[0];
//          	$(polygon).attr('fill','#eff7ff');
//          })
//		},
//		error: function() {
//			console.log('error');
//		}
//	});


    //show_box
    var bool = false;
    var showBox = '<div class="show_box"><p id=' + "fz" + '><img src="/images/fzz.png">复制快讯</p><p id=' + "xl" + '><img src="/images/wbb.png">新浪微博</p><p><img src="/images/wxx.png">微信扫一扫</p><p class="ewm"></p></div>';
    $(".content").on("click", ".p", function(e) {
        e.preventDefault();
        bool = !bool;
        if(bool && $('.show_box').css('display')!='block') {
            $(this).parent().parent().append(showBox);
            var newsflash_id = $(this).parent().parent().data('id');
            var img_path_type= $(this).parent().parent().data('path_type');
            var timeId = $(this).parent().parent().attr('id');

            var div = $(this).parent().parent().find('.show_box').find('.ewm')[0];
            var qrcode = new QRCode(div,{
                text:"http://"+window.location.host+"/kuaixun?newsid=" + newsflash_id + "&issueMonth="+formatM(timeId) + "&path_type="+img_path_type,
                width:100,
                height:100
            });
        } else {
            $(this).parent().parent().find($('.show_box')).remove();
        }
    })
    $(document).click(function(e){
//		e.stopPropagation();
        if($('.show_box').css('display')=='block' & e.target.className != 'p'){
            $('.show_box').remove();
            bool = false;
        }
        if($('.news .c-header ul').css('display')=='block' & e.target.tagName.toLowerCase() != 'ul'){
            $('.news .c-header ul').css('display','none');
        }
    })

    //复制
    var clipboard = new Clipboard('#fz', {
        text: function(e) {
            return e.parentNode.parentNode.childNodes[2].innerHTML + "http://" + window.location.host;
        }
    });
    clipboard.on('success', function(e) {
        $('.success').animate({
            'opacity': '1'
        }, 1000);
        $('.success').animate({
            'opacity': '0'
        }, 1000);
        $('.show_box').remove();
        bool = false;
    });
    clipboard.on('error', function(e) {
        alert("浏览器不支持此功能，请手动复制");
    });

    //分享
    $(".news").on("click", "#xl", function(e) {
        var title = $(this).parent().parent().find('.orange').text() || $(this).parent().parent().find('li:nth-child(2)').text();
        var imgURL = $(this).parent().prev().find('p').attr('imgUrl');
        shareToXl(title.slice(0,160),window.location.href,imgURL);
        $('.show_box').remove();
        bool = false;
    })

    //图片悬停
    $(window).scroll(function(){
        if($(window).scrollTop() > ($('.right').height()+20+$('header').height()) && $(window).scrollTop()+600 < $('.content').height()){
            $('.right .ewm').removeClass('abso');
            $('.right .ewm').addClass('fixed');
        }else if($(window).scrollTop()+600 >= $('.content').height()){
            $('.right .ewm').removeClass('fixed');
            $('.right .ewm').addClass('abso');
        }else{
            $('.right .ewm').removeClass('fixed');
            $('.right .ewm').removeClass('abso');
        }
    });

    //详情页打开
    $('.kuaixun_list').on('click', '.orange', function() {
        var id = $(this).parent().data('id');
        window.open('/home/newsflashpc/detail?id=' + id);
    })

//搜索框
    //两个搜索框内容绑定
    $('.news>.c-header input').bind('input propertychange',function(){
        var v = $('.news>.c-header input').val();
        $('.news .topFix input').val(v);
    });
    $('.news .topFix input').bind('input propertychange',function(){
        var v = $('.news .topFix input').val();
        $('.news>.c-header input').val(v);
    });
    //输入内容搜索
    var flag;
    $('.news input').on('compositionstart',function(){//输入中文开始
        flag = true;
    });
    $('.news input').on('compositionend',function(){//输入中文结束
        flag = false;
        if(!flag){
            var v = $('.news>.c-header input').val();
            $('.news .c-header ul').css('display','block');
            // search(v);
            keyDown();
        }
    });
    $('.news input').bind('input propertychange',function(e){
        if(!flag){
            var v = $('.news input').val();
            $('.news .c-header ul').css('display','block');
            // search(v);
            keyDown();
        }
    });
    //搜索按钮
    $('.news .c-header button').click(function(){
        var k = $('.news .c-header input').val();
        var url = '/home/newsflashpc/find?value=' + k;
        if(k == ''){
            return;
        }

        if(location.href.indexOf('/home/newsflashpc/find') != -1){
            window.location.href=url;
        }else{
            window.open(url);
        }
    });
    //搜索列表点击事件
    function keyDown(){
        document.onkeydown=function(e){
            var e = event || window.event || arguments.callee.caller.arguments[0];
            var li = $('.news .c-header ul li'), fli = li.filter('.focus');
            li.removeClass('focus');
            if(e && e.keyCode==13){ // enter 键
                var v;
                if (fli.length > 0) {
                    $('.news input').val(fli[0].innerText);
                    fli.parent().hide();
                    v = $(fli).attr('title');
                }else{
                    v = $('.news input').val();
                }

                var k = $('.news input').val();
                var findUrl = '/home/newsflashpc/find?key=' + v + '&value=' + k;

                if(k == ''){
                    return;
                }

                if(location.href.indexOf('/home/newsflashpc/find') != -1){
                    window.location.href=findUrl;
                }else{
                    window.open(findUrl);
                }
            }else if(e && e.keyCode==38){//up 键
                if (fli.length == 0 || fli.prev().length==0) li.filter(':last-child').addClass('focus');
                else fli.prev().addClass('focus');
            }else if(e && e.keyCode==40){//down 键
                if (fli.length == 0 || fli.next().length==0) li.filter(':first-child').addClass('focus');
                else fli.next().addClass('focus');
            }
        }
    }

    //gotop
    $('.goTop').click(function(){
        $('body,html').animate({ scrollTop: 0 }, 500);
    });
    $(window).scroll(function(){
        if($(window).scrollTop() > ($('.c-header').height()+80+$('header').height()) && $(window).scrollTop()+1220 < $('body').height()){
            $('.goTop').css({
                'position':'fixed',
                'bottom':'50px',
                'right':$(window).width() - $('.news').offset().left - $('.news').width()-80
            });
        }else if($(window).scrollTop()+1220 > $('body').height()){
            $('.goTop').css({
                'position':'absolute',
                'right':'-40px',
                'bottom':'-40px'
            });
        }else if($(window).scrollTop() < ($('.c-header').height()+40+$('header').height())){
            $('.goTop').css({
                'position':'absolute',
                'right':'-40px',
                'bottom':'-40px'
            });
        }
    })
});

//搜索内容
function search(val){
    $.ajax({
        type:"get",
        url:"/api/news/keymap?key="+val,
        async:true,
        success:function(data){
            if(val.indexOf('(') != -1){
                return;
            }
            $('.news .c-header ul li').remove();
            var msg = data.data;
            var keyWordReg = new RegExp(val,'img');
            $.each(msg, function(k,value) {
                if(value.show_words.match(keyWordReg)){
                    var keystr = value.show_words.match(keyWordReg)[0];
                    value.show_words = value.show_words.replace(keyWordReg,'<span style="color:#728fb7;">'+keystr+'</span>');
                }
                $('.news .c-header ul').append('<li title='+value.query+'>'+value.show_words+'</li>');
            });
        }
    });
}
$('.news .c-header ul').on('click','li',function(){
    var k = $(this).text();
    var v = $(this).attr('title');
    var findUrl = '/home/newsflashpc/find?key=' + v + '&value=' + k;
    $('.news .c-header input').val(k);
    if(location.href.indexOf('/home/newsflashpc/find') != -1){
        window.location.href=findUrl;
    }else{
        window.open(findUrl);
    }
});

//时间戳转换为当前时间
function add0(m) {
    return m < 10 ? '0' + m : m
}
//时:分
function format(shijianchuo) { //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo*1000);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    var sj = y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
    var arr = sj.split(' ')[1].split(':');
    var str = arr[0] + ':' + arr[1];
    return str;
}
//完整时间
function formatT(shijianchuo) { //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo*1000);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    var sj = y + '年 ' + add0(m) + '月' + add0(d) + '日 ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
    return sj;
}
//年，月
function formatM(shijianchuo) { //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo*1000);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var sj = y+''+add0(m);
    return sj;
}
//带周的时间
function formatTw(shijianchuo) { //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo*1000);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var w = time.getDay();
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    var weekday=new Array(7);
    weekday[0]="星期天";
    weekday[1]="星期一";
    weekday[2]="星期二";
    weekday[3]="星期三";
    weekday[4]="星期四";
    weekday[5]="星期五";
    weekday[6]="星期六";
    var sj = add0(m) + '月' + add0(d) + '日·' + add0(weekday[w]);
    return sj;
}

//判断是否为当天
function isToday() {
    var arr=[];
    $.each($('.kuaixun_list .time'), function(k,v) {
        arr.push($(v).next().find('ul:nth-child(1)').attr('id'));
        var str = arr[0];
        //今天
        var today = new Date(new Date().setHours(0, 0, 0, 0)).getTime().toString().substring(0,10);
        var oneday = 60 * 60 * 24;
        // 昨天
        var yesterday = today - oneday;
        if(str >= today && $('.time').find('span').length ==0) {
            $('.kuaixun_list .time').prepend('<span>今天·</span>');
        }
        console.log(str,today);
    });
}

//新浪分享
function shareToXl(title, url, picurl) {
    var sharesinastring = 'http://v.t.sina.com.cn/share/share.php?title=' + encodeURIComponent(encodeURIComponent(title)) + '&url=' + url + ' & content=utf-8&sourceUrl=' + url + '&pic=' + picurl;
    window.open(sharesinastring, 'newwindow', 'height=400,width=400,top=100,left=100');
}

//解析URL
function getUrlGet() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if(url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for(var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

function getUrlParam(key){
    // 获取参数
    var url = window.location.search;
    // 正则筛选地址栏
    var reg = new RegExp("(^|&)"+ key +"=([^&]*)(&|$)");
    // 匹配目标参数
    var result = url.substr(1).match(reg);
    //返回参数值
    return result ? decodeURIComponent(result[2]) : null;
}